﻿using System;
using System.Web;
using NHibernate;
using NHibernate.Cfg;

namespace SNARF.Framework.ActiveRecord
{
    public sealed class StaticSessionProvider : SessionProviderBase
    {
       
        private readonly ISessionFactory sessionFactory;
        private ISession currentSession;
        public event EventHandler SessionClosing;

        public StaticSessionProvider() : base()
        {            
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
            
        }

        void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            if (this.SessionClosing != null)
                this.SessionClosing(this, e);

            if (this.currentSession != null)
                this.currentSession.Close();
        }

        public override ISession CurrentSession
        {
            get
            {

                if (currentSession == null)
                {
                    currentSession = sessionFactory.OpenSession();
                    currentSession.FlushMode = FlushMode.Never;
                }

                return currentSession;
            }
        }

        public void CloseSession()
        {

            if (currentSession == null)
            {
                // No current session
                return;
            }

            currentSession.Close();

        }

        public void CloseSessionFactory()
        {
            if (sessionFactory != null)
            {
                sessionFactory.Close();
            }
        }
    }
}
